package com.powernode.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.shop.constant.RoleConstant;
import com.powernode.shop.domain.SysRole;
import com.powernode.shop.mapper.SysRoleMapper;
import com.powernode.shop.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;

/**
* @author ZHAOZHENYU
* @since 2022/10/10
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired(required = false)
    private SysRoleMapper sysRoleMapper;

    /**
     * 重写mp的list方法 存储到redis
     * @return
     */
    @Override
    public List<SysRole> list() {

        String roleStrs = redisTemplate.opsForValue().get(RoleConstant.SYS_ROLE_PREFIX);
        List<SysRole> roleList = null;
        if (StringUtils.hasText(roleStrs)){
            // 用fastJson转换为将json串集合
            roleList = JSON.parseArray(roleStrs, SysRole.class);
        }else {
            roleList = sysRoleMapper.selectList(null);
            if (!CollectionUtils.isEmpty(roleList)){
                String jsonString = JSON.toJSONString(roleList);
                redisTemplate.opsForValue().set(RoleConstant.SYS_ROLE_PREFIX, jsonString, Duration.ofHours(1));
            }
        }
        return roleList;
    }

}
